<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title>Social Mobile</title>
<!-- jQuery and jQuery Mobile -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script	src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>

<script	src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script type="text/javascript" src="js/jquery.ui.map.js"></script>
<script type="text/javascript" src="js/infobox.js"></script>
<script type="text/javascript" src="js/markerclusterer.js"></script>


<link rel="stylesheet" href="css/mobile-style.css" />
<script type="text/javascript" src="js/social-mobile.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>

<script type="text/javascript">
	var activedPage = "login-mobile-page";
	var userNuLatitude;
	var userNuLogintude;
	var userIndex;
	var userNuRaiusGps;
	var userIsShowMyPosition;
	var nativeApplicationPosition = "";

	var latitudeGlobal = "-15.7762991";
	var longitudeGlobal = "-47.7966223";
	var markerPosition = "";
	var map;
	var idInfoBoxAberto;
	var infoBox = [];
	var markers = [];
	var latlngbounds;
	var browserSupportFlag;
	var arrUsers = new Array() ;

	
	function chagePage(paramPage) {
		
		activedPage = paramPage;
		location.href = paramPage;
		
		if (activedPage == "#map-page") {
			initialize();	
		}
		
	}
	
	//SCRIPTS MAPA
	
	function initialize() {
	  var mapOptions = {
	    zoom: 5,
	    center: new google.maps.LatLng(latitudeGlobal, longitudeGlobal),
	    mapTypeId: google.maps.MapTypeId.ROADMAP,
	    streetViewControl: false
	  };

	  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

     //Definir altura do DIV do mapa
     $('#map-canvas').height($(window).height()-$('#title-header').height()-10);
     loarUsersProfile();
	 myPosition();
  
	}
	
	
	
	function abrirInfoBox(id, marker) {
		if ((typeof(idInfoBoxAberto) == 'string' || typeof(idInfoBoxAberto) == 'numeric') && typeof(infoBox[idInfoBoxAberto]) == 'object') {
			infoBox[idInfoBoxAberto].close();
		}

		infoBox[id].open(map, marker);
		idInfoBoxAberto = id;
	}	

	function showDetailProfile(ponto) {
		strDetail = "<div><table border='0'><tr><td style='vertical-align: top' rowspan='4'><img src='"+returnStrImageProfile(ponto.dsImgUser) + "'></td><td colspan='2' class='nameProfile'>" + ponto.dsProfileName + "</td></tr><tr><td class='detailProfile'>Nome:</td><td>" + ponto.dsName + "</td></tr><tr><td class='detailProfile'><b>Idade:</b></td><td>" + ponto.nuAge + "</td></tr><tr><td class='detailProfile'><b>Útima posição:</b></td><td>" + ponto.dtLastUpdatedGps + "</td></tr></table></div>";
		return strDetail;
		}
	
	function carregarPontos(center) {
		clearOverlays();
		try {
		$.getJSON('/social-mobile-web/rest/users', function(pontos) {
			latlngbounds = new google.maps.LatLngBounds();

			$.each(pontos.userDto, function(index, ponto) {
				if (ponto) {
					createMarker(ponto.nuId, ponto.nuLatitude, ponto.nuLongitude, ponto.dsName, returnStrImageMarker(ponto.dsImgUser), showDetailProfile(ponto));
				}
			});
			var markerCluster = new MarkerClusterer(map, markers);
			
			//map.fitBounds(latlngbounds);
			if (center != false) {
				map.setZoom(5);
				latlngbounds.extend(marker.position);
			}
			
		});
		} catch (e) {
			//alert(e);
		}
	}
	
	function clearOverlays() {
		  if (markers) {
		    for (i in markers) {
		    	markers[i].setMap(null);
		    }
		    markers = [];
		  }
		}	

	function createMarker(pid, platitude, plongitude, description, pimg, pinfo) {
		
		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(platitude, plongitude),
			title: description,
			icon: pimg
		});

		var myOptions = {
			content: pinfo,
			minWidth: 150,
			pixelOffset: new google.maps.Size(-150, 0)
    	};

		infoBox[pid] = new InfoBox(myOptions);
		infoBox[pid].marker = marker;
		infoBox[pid].listener = google.maps.event.addListener(marker, 'click', function (e) {
			abrirInfoBox(pid, marker);
		});

		markers.push(marker);
		
	}

	function centerAt(latitude, longitude) {
		myLatlng = new google.maps.LatLng(latitude, longitude);
		map.panTo(myLatlng);
	}
	
	function setGlobalLatLogMobile(latitude, longitude) {
		latitudeGlobal = latitude;
		longitudeGlobal = longitude;
		nativeApplicationPosition = "true";
		$("#txt-profile-name")[0].innerHTML = latitude;
	}
	
	function setGlobalLatLog(latitude, longitude) {
		latitudeGlobal = latitude;
		longitudeGlobal = longitude;
	}


	 function myPosition (focus) {
		 try {
			 $("#txt-profile-name")[0].innerHTML = "My Position S";
			 if (nativeApplicationPosition != "") {
	             setGlobalLatLog(latitudeGlobal, longitudeGlobal);
				 initialLocation = new google.maps.LatLng(latitudeGlobal,longitudeGlobal);
	         
				 $("#txt-profile-name")[0].innerHTML = "Nativo Position";
				 
	             updateUserData();
	             
	             if (focus == true) {
	                 map.setCenter(initialLocation);
	                 map.setZoom(15);
	                 $("#txt-profile-name")[0].innerHTML = "MEXE NO MAPA";
	         		}                
	             
			 } else if (navigator.geolocation) {
				 $("#txt-profile-name")[0].innerHTML = "Browser Position";
	           browserSupportFlag = true;
	           navigator.geolocation.getCurrentPosition(function(position) {
	             initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
	             setGlobalLatLog(position.coords.latitude, position.coords.longitude);
	             
	             updateUserData();
	             
	             if (focus == true) {
	                 map.setCenter(initialLocation);
	                 map.setZoom(15);
	         		}    
	             
	           }, function() {
	             return;
	           });
	         }
	         // Browser doesn't support Geolocation
	         else {
	        	 $("#txt-profile-name")[0].innerHTML = "FEZ NADA";
	               return;
	         }
		 } catch (e) {
				//Error
		 }
         
	 }    
	 
function updateUserData() {
	try {
		if (activedPage == "#map-page") {
			userNuLatitude = latitudeGlobal;
			userNuLongitude = longitudeGlobal;
			userIndex = $.cookie("userSelected");
			userNuRaiusGps = 10;
			userIsShowMyPosition = "S";
		
			
			//$('#slider2').val(3);
			//$('#slider2').slider('refresh');
			
				var $form = $("#frm-user");
				userNuRaiusGps = $form.find( 'input[name="sliderRaius"]' ).val();
				userIsShowMyPosition = $form.find( 'select[name="isShowMyPosition"]' ).val();
				url = $form.attr( 'action' );
			 
			  /* Send the data using post */
			  var posting = $.post( url, { 'nuRaiusGps': userNuRaiusGps, 'nuLatitude': userNuLatitude, 'nuLongitude': userNuLongitude, 'isShowMyPosition': userIsShowMyPosition, 'userIndex': userIndex } );
		
			  /* Put the results in a div */
			  posting.done(function( data ) {
				if (data != "sucess") {
					//location.href = "index.html"
					chagePage("#login-mobile-page");
				} else {
					 //setTimeout("updateUserData();", 60000);
				  	 carregarPontos(false);
				}
			    
			  });	  
		}
	  
	} catch (e) {
		//Error
	}

}


function loarUsersProfile() {
	try {
		if (activedPage == "#map-page") {
			idx = 0;
			$.getJSON('/social-mobile-web/rest/users/profileUsers', function(users) {
				
				$.each(users.userDto, function(index, user) {
					if (user) {
						arrUsers[idx] = new Array() ;
						arrUsers[idx]['DS_NAME'] = user.dsName;
						arrUsers[idx]['NU_AGE'] = user.nuAge;
						arrUsers[idx]['DS_IMG_USER'] = user.dsImgUser;
						arrUsers[idx]['DS_PROFILE_NAME'] = user.dsProfileName;		
						
						idx++;
					}
		
				});
				createTableUser();
				setUser($.cookie("userSelected"));	  
			});
		}
	} catch (e) {
		//alert(e);
	}
}

var lineSelected;
function setUser(pUser) {
	//Lembrar de colocar o código setUser($.cookie("userSelected")); no final ou no onload
	var obj;
	if (!pUser) {
		pUser = 0;
	}

	for (i=0; i< arrUsers.length; i++) {
		obj = $("#user_line_"+ i )[0];
		if (i == pUser) {
			obj.style.backgroundColor="#3B0B0B";
		} else {
			obj.style.backgroundColor="#424242";
		}
	}

	if (arrUsers.length > 0) {
		displayProfileSelected(pUser);
	}
	$.cookie("userSelected", pUser, {expires: new Date(2020, 01, 31, 11, 00, 00)});
}

function displayProfileSelected(pUser) {
	$("#img-profile")[0].src = "imageprofile?img=" + arrUsers[pUser]['DS_IMG_USER'] + ".gif";
	$("#txt-profile-name")[0].innerHTML = arrUsers[pUser]['DS_PROFILE_NAME'];
	$("#txt-user-name")[0].innerHTML = arrUsers[pUser]['DS_NAME'];
	$("#txt-age-name")[0].innerHTML = arrUsers[pUser]['NU_AGE'];

}

function createTableUser() {
	for (i=0; i< arrUsers.length; i++) {
		$("#table-users").last().append("<tr onclick='setUser("+i+");' id='user_line_"+i+"'><td class='displayLabel'><img src='imageprofile?img="+ arrUsers[i]['DS_IMG_USER'] +".gif' width='30' /></td><td>&nbsp;</td><td class='displayLabelValue' width='100%'>"+ arrUsers[i]['DS_NAME'] +"</td></tr>");

	}
}	

		</script>

<style>
#map-page {
	padding: 0px;
	width: 100%;
	height: 100%;
	overflow: hidden;
}

</style>
</head>
<body>


	<!-- Login -->
	<div data-theme="a" data-role="page" id="login-mobile-page">
		<div data-role="content">

			<center>
			<img alt="" src="img/logossw.png">
			<br>
			<img src="img/txtssw.png">
			<form id="frm-login" action="/social-mobile-web/rest/login"  data-ajax="false">
				<div data-role="fieldcontain">
					<label for="dsLogin"> Usuário </label> <br/> <input name="dsLogin"
						id="dsLogin" placeholder="" value="" type="text">
				</div>
				<div data-role="fieldcontain">
					<label for="dsPassword"> Senha </label> <br/> <input name="dsPassword"
						id="dsPassword" placeholder="" value="" type="password">
				</div>
				<input id="login-submit" type="submit" value="Conectar">
			</form>
			
			<div id="msg-display"></div>
		</div>
		<div data-position="fixed">
			<center><i>Utilze o seu usuário e senha do CRS.</i></center>
		</div>
	</div>

	<!-- Home -->
	<div data-role="page" id="map-page">

		<div data-role="header">
			<a href="#esquerda" data-icon="bars" data-iconpos="notext"></a>
			<h1><img src="img/txtssw.png" ></h1>
		</div>

		<div data-role="content" style="padding: 0px;">

			<div id="map-canvas"></div>
			<div id="ic_mi" style="position:absolute;right:5px;bottom:30px;"><img src="img/ic_my_pos.png" border="0" width="40" onclick="myPosition(true);"></div>
		</div>




	<div data-role="panel" data-theme="a" id="esquerda">
			<ul data-role="listview" data-inset="false" 
				data-divider-theme="a" data-icon="false">

				<table>
				<tr>
					<td style="vertical-align: top"><img src="img/logossw_ic.png" id="img-profile" width="50"/></td>
					<td style="vertical-align: top">
					<table>
					<tr>
						<td colspan="2" class="displayProfileName"><div id="txt-profile-name"></div></td>
					</tr>					
					<tr>
						<td class="displayLabel">Usuário:</td>
						<td class="displayLabelValue"><div id="txt-user-name"></div></td>
					</tr>
					<tr>
						<td class="displayLabel">Idade:</td>
						<td class="displayLabelValue"><div id="txt-age-name"></div></td>
					</tr>					
					</table>
					</td>
				</tr>
				</table>
				
				<div class="displayMenuMain">Configurações</div><br>				



			<form id="frm-user" action="/social-mobile-web/rest/users/updateUsers"  data-ajax="false">
			<div class="displayProfileName">Exibir sua posição no mapa:</div></br>
			<select name="isShowMyPosition" id="isShowMyPosition" data-theme="a"
				data-role="slider" data-mini="true">
				<option value="N">Off</option>
				<option value="S" selected="selected">On</option>
			</select> 
			<br><br>
			<div class="displayProfileName">Defina um raio pra pesquisa:</div><br>
			<input type="range" name="sliderRaius" id="sliderRaius" value="50" min="0" max="100" data-highlight="true" data-mini="true" />
			</form>
			
				<div class="displayMenuMain">Usuários do perfil</div>

				<table width="100%" border="0" cellpadding="0" cellspacing="0" id="table-users">
				</table>

			</ul>
		</div>


	</div>
	
<script>

/* attach a submit handler to the form */
$("#frm-login").submit(function(event) {

	showLoadingMsg();

	/* stop form from submitting normally */
  event.preventDefault();
 
  /* get some values from elements on the page: */
  var $form = $( this ),
      login = $form.find( 'input[name="dsLogin"]' ).val(),
      pwd = $form.find( 'input[name="dsPassword"]' ).val(),
      url = $form.attr( 'action' );
 
  /* Send the data using post */
  var posting = $.post( url, { 'dsLogin': login, 'dsPassword': pwd } );
 
  /* Put the results in a div */
  posting.done(function( data ) {
	if (data == "sucess") {
		//location.href = "users.html"
		chagePage("#map-page");
	} else {
		hideLoadingMsg();
		$("#msg-display").html(data);
	}
    
  });
});
</script>	
</body>
</html>
